package com.caiya.controller;

import com.caiya.MicroserviceGatewayZuulAggregationApplication;
import com.caiya.cart.Res;
import com.caiya.cart.entity.CartUser;
import com.caiya.service.AggregationService;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import rx.Observable;
import rx.Observer;

import java.util.HashMap;

/**
 * Created by Administrator on 2019/4/8 0008.
 */
@RestController
public class AggregationController {
    public static final Logger LOGGER = LoggerFactory.getLogger(MicroserviceGatewayZuulAggregationApplication.class);

    @Autowired
    private AggregationService aggregationService;

    @GetMapping("/aggregate/{id}")
    public DeferredResult<HashMap<String,Res>> aggregate(@PathVariable Long id){
        Observable<HashMap<String,Res>> result =  this.aggregateObservable(id);
        return this.toDeferredResult(result);
    }

    public Observable<HashMap<String, Res>> aggregateObservable(Long id){
        return rx.Observable.zip(
                this.aggregationService.getUserById(id),
                this.aggregationService.getMovieUserByUserId(id),
                (cartUser,movieUser) ->{
                    HashMap<String,Res> map = Maps.newHashMap();
                    map.put("cartUser",cartUser);
                    map.put("movieUser",movieUser);
                    return map;
                }
        );
    }

    public DeferredResult<HashMap<String,Res>> toDeferredResult(Observable<HashMap<String, Res>> details){
        DeferredResult<HashMap<String,Res>> result = new DeferredResult<>();

        details.subscribe(new Observer<HashMap<String, Res>>() {
            @Override
            public void onCompleted() {
                LOGGER.info("完成。。。");
            }

            @Override
            public void onError(Throwable throwable) {
                LOGGER.info("错误",throwable);
            }

            @Override
            public void onNext(HashMap<String, Res> stringCartUserHashMap) {
                result.setResult(stringCartUserHashMap);
            }
        });
        return result;
    }
}
